package scau.erps.service.impl;
import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.service.IdEntityService;

import scau.erps.app.Erps;
import scau.erps.entity.Line;
import scau.erps.entity.Product;
import scau.erps.entity.Sand;
import scau.erps.entity.Store;
import scau.erps.service.ProductService;
import scau.erps.service.ResearchService;
import scau.erps.util.CalculateQuarter;
import scau.erps.util.Trans;
/**
 * 产品服务实现类
 * @author outsider
 *  
 */

public class ProductServiceImpl extends IdEntityService<Product> implements ProductService {

    private final static int[][] MATERIALCOST={{1,0,0,0},{0,1,0,0},{0,1,2,0},{0,1,2,1}};  //原材料消耗
    private final static int[][] PROCESSINGCOST={{1,1,1,1},{2,1,1,1},{3,2,1,1},{4,3,2,1}};  //加工费
	private ResearchService researchService = Erps.getIocInstance().get(ResearchServiceImpl.class);

	/**
	 * 更新在制品状态 返回完成各产品的数量 Beryl、Crystal、Ruby、Sapphire依次对应数组0~3位置
	 * @author  outsiders
	 */    
	public int[] updateProduct(int team_Id) {
		String time=Erps.getSand().getTime();
		int[] count=new int[4];
		List<Product> list=this.dao().query(Product.class, Cnd.where("team_Id", "=", team_Id).and("completeTime","=",time));
        for(Product product:list){
        	product.setStatus("成品");
        	if (product.getProduct().equals("Beryl")) count[0]=count[0]+1;
        	if (product.getProduct().equals("Crystal")) count[1]=count[1]+1;
        	if (product.getProduct().equals("Ruby")) count[2]=count[2]+1;
        	if (product.getProduct().equals("Sapphire")) count[3]=count[3]+1;
            Line line=this.dao().fetch(Line.class, (team_Id-1)*8+product.getLineNo());
            line.setStatus("空闲");
        	
            this.dao().update(line);
        	this.dao().update(product);
        }
      return count;
	}
	/**
	 * 更新某条product记录状态
	 * @author  outsiders
	 */  
	public void updateProduct(Product product){
		this.dao().update(product);
	}
	/**
	 * 提交新的生产产品需求
	 * @author  outsiders
	 */  	
	public void makeNewProduct(Product product) {
		this.dao().insert(product);	
	}

	/**
	 * 返回处于小组处于某状态的某产品 并按成本升序排列
	 * @author  outsiders
	 */ 
	public List<Product> getProductByTypeAndStatus(int team_Id,String product,String status){
		SqlExpressionGroup e1 = null;
		SqlExpressionGroup e2 = null;
		SqlExpressionGroup e3 = null;
		if(team_Id != 0){
			e1 = Cnd.exps("team_Id", "=", team_Id);			
		}
		if(	product != null){
			e2 = Cnd.exps("product", "=", product);
		}
		if(status != null){
			e3 = Cnd.exps("status", "=", status);
		}
		return this.query(Cnd.where(e1).and(e2).and(e3).asc("cost"), null);
	}
	/**
	 * 返回处于小组由某条生产线生产处于某状态的产品
	 * @author  outsiders
	 */ 
	public List<Product> getProductByLineNoAndStatus(int team_Id, int lineNo,String status) {
		SqlExpressionGroup e1 = null;
		SqlExpressionGroup e2 = null;
		SqlExpressionGroup e3 = null;
		if(team_Id != 0){
			e1 = Cnd.exps("team_Id", "=", team_Id);			
		}
		if(	lineNo != 0){
			e2 = Cnd.exps("lineNo", "=", lineNo);
		}
		if(status != null){
			e3 = Cnd.exps("status", "=", status);
		}
		return this.query(Cnd.where(e1).and(e2).and(e3), null);
		
	}
	/**
	 * 提交新生产需求的预处理 
	 * 返回正数表示正常
	 * 返回1~-4表示缺M1~M4原材料 
	 * 返回-5表示缺少Beryl
	 * 返回-6表示现金不足
	 * 返回-7表示产品未研发完成
	 * @author  outsiders
	 */  
	public int preNewProduct(int team_Id,String productType,int LineNo,int num,Line line){

	    Store store=Erps.getStore();
		Sand sand=Erps.getSand();
		String type=line.getType();
		int cost = 0;
		String manufacturingTime,completeTime;
		int lineTypeFlag=Trans.trans(type);
		int productFlag=Trans.trans(productType);
		int m1=store.getM1(),m2=store.getM2(),m3=store.getM3(),m4=store.getM4(); //获取仓库中各原材料储量
		int[] stored={m1,m2,m3,m4};
		int cash=sand.getCash();                                       //获取现金

		//生产Beryl、Ruby、Sapphire时
		if (productType.equals("Crystal")==false){
			  for (int i=0;i<=3;i++){                                     //判断原材料是否充足
				  cost=cost+MATERIALCOST[productFlag][i];
				  if (stored[i]<(num*MATERIALCOST[productFlag][i])) return -(i+1);				  
			    }
		  if (cash<(num*PROCESSINGCOST[productFlag][lineTypeFlag]))  return -6;     //判断现金是否充足
		  if ((productType.equals("Crystal") && researchService.findResearchs(team_Id, "Crystal") < 4))  //判断研发是否完成 
			  return -7;
		  if ((productType.equals("Ruby") && researchService.findResearchs(team_Id, "Ruby") < 6))   
			  return -7;
		  if ((productType.equals("Sapphire") && researchService.findResearchs(team_Id, "Sapphire") < 8))
			  return -7;
		  
			  				
		  cash=cash-num*PROCESSINGCOST[productFlag][lineTypeFlag];    //支付加工费与材料
		  sand.setCash(cash);
		  for (int i=0;i<=3;i++){                                     
              stored[i]=stored[i]-(num*MATERIALCOST[productFlag][i]);
              if (i==0) store.setM1(stored[i]);
              if (i==1) store.setM2(stored[i]);
              if (i==2) store.setM3(stored[i]);
              if (i==3) store.setM4(stored[i]);
		    }
          this.dao().update(store);
          this.dao().update(sand);
          
		  cost=cost+PROCESSINGCOST[productFlag][lineTypeFlag];      //计算单个成本
		  manufacturingTime=sand.getTime();
		  completeTime=CalculateQuarter.getProductCompleteTime(sand.getTime(), type);
		  }
		  //生产Crystal时
		else{
		   int tot=0;
		   if (stored[1]<num) return -2;                                     //判断原材料是否充足
		   List<Product> berylList=getProductByTypeAndStatus(team_Id, "Beryl", "成品");
		   tot=berylList.size();  //统计可用的Beryl数量
		   if (tot<num)  return -5;	 
		   cost=3+PROCESSINGCOST[productFlag][lineTypeFlag];               //计算单个成本
		   if (cash<num*cost)  return -6;                                       //判断现金是否充足
		   if (researchService.findResearchs(team_Id, "Crystal") < 4)     //判断研发是否完成
			   return -7;
		   
		   int temp=num;
		   for (Product product:berylList) {                         //更新被使用的Beryl库存
			   if (temp==0) break;
			   if (temp>0){
				   product.setStatus("零件");
				   updateProduct(product);
			   }
			   temp--;
		   }
		   cash=cash-num*PROCESSINGCOST[productFlag][lineTypeFlag];                                                //支付加工费与材料
		   sand.setCash(cash);
		   store.setM2(store.getM2()-num); 
		   manufacturingTime=sand.getTime();
		   completeTime=CalculateQuarter.getProductCompleteTime(sand.getTime(), type);
		}
		   Product product=new Product(team_Id, productType, line.getLineNo(), type, manufacturingTime, completeTime, cost, "在制品");
		   makeNewProduct(product);
		   line.setStatus("生产");
		   line.setIsNew(0);
		   this.dao().update(line);
	       this.dao().update(store);
	       this.dao().update(sand);
	       return 0;

	}
	public Product getProductByID(int ID){
		return this.fetch(ID);
	}
	
	
}
